package com.wowangz.cms.user.api;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.CommonCrypto;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.api.UserContext;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.JedisUtil;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.systemmanage.passwordpolicy.pojo.PasswordPolicyHistory;
import com.wowangz.cms.systemmanage.passwordpolicy.service.PasswordPolicyHistoryService;
import com.wowangz.cms.user.pojo.User;
import com.wowangz.cms.user.service.LoginService;
import com.wowangz.cms.user.service.UserService;

/**
 * @author HUANGYUAN
 * @时间 2015年7月30日 上午9:58:42
 * @包名称 com.wowangz.cms.login.api
 * @描述 用户已经登录成功。在主界面上修改密码
 */
@Scope("prototype")
@Controller
public class ModifyController extends BaseController {

	/**
	 *
	 * @author HUANGYUAN
	 * @时间 2015年7月30日 上午10:00:21
	 * @return
	 * @描述 跳转到重置页面
	 */
	@RequestMapping(value = "/login/intoResetPassword.json")
	public String intoResetPassword(HttpServletRequest request, Model model) {
		final UserContext userContext = getUserContext();
		Long userid = 0l;
		if (userContext != null) {
			final User user = userContext.getLoginUser();
			if (user != null) {
				userid = user.getId();
			}
			model.addAttribute("userid", userid);
		}
		return "resetpassword";
	}

	/**
	 * @author HUANGYUAN
	 * @时间 2015年7月30日 上午10:00:48
	 * @param request
	 * @param response
	 * @描述 修改登录的密码
	 */
	@RequestMapping(value = "/login/modifyPassword.json", method = RequestMethod.POST)
	public void modifyPassword(HttpServletRequest request, HttpServletResponse response) {
		final AjaxDataEntity entity = new AjaxDataEntity();
		UserContext userContext = getUserContext();
		// 获得用户的Service
		final UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
		// 设置错误信息
		String errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.java.alert20");
		if (userContext == null) {
			userContext = new UserContext();
			userContext.setErrorMessage(errorMessage);
		} else {
			try {
				final Long userid = userContext.getLoginUser().getId();
				final User user = userService.queryUserById(String.valueOf(userid));
				// 旧密码
				final String old_password = request.getParameter("oldPassword");
				// 新密码
				final String new_password = request.getParameter("userpassword");
				// 加密后的旧密码
				String password = CommonCrypto.encryptSHAEncoder(old_password);
				if (user != null) {
					// 判断输入的密码与原来的密码是否一致
					final String oldpassword = user.getPassword();
					if (StringUtils.equals(password, oldpassword)) {
						// 加密新密码
						password = CommonCrypto.encryptSHAEncoder(new_password);
						user.setPassword(password);
						user.setModifytime(new Date());
						user.setModifyuserid(userContext.getLoginUser().getId());
						user.setPwdchangedate(new Date());
						userService.modify(user);
						// 保存密码历史
						PasswordPolicyHistory history = new PasswordPolicyHistory();
						history.setLoginname(user.getLoginname());
						history.setPassword(oldpassword);
						history.setInputtime(new Date());
						final PasswordPolicyHistoryService service = (PasswordPolicyHistoryService) IssTransactionContainer.getInstance(
								PasswordPolicyHistoryService.class, true);
						service.insertPasswordHistory(history);
						// 获得redis中的缓存数据
						final User user1 = (User) JedisUtil.getPublicDataObject(userContext.getLoginUser().getLoginname(), User.class,
								JedisUtil.STORE_LOGINUSER);
						user1.setPassword(password);
						user1.setIsexpire(SysConstant.Boolean.FALSE);
						user1.setIsprompt(SysConstant.Boolean.FALSE);
						LoginService loginService = (LoginService) IssTransactionContainer.getInstance(LoginService.class, false);
						loginService.updateUserByLoginName(user1);
						// 将信息插入到缓存数据当中去
						JedisUtil.insertPublicDataObject(user1.getLoginname(), user1, JedisUtil.STORE_LOGINUSER);
						// 设置修改成功后的提示信息
						final String infoMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.jsp.alert22");
						userContext.setInfoMessage(infoMessage);
					} else {
						errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.jsp.alert23");
						userContext.setErrorMessage(errorMessage);
					}
				} else {
					// 设置用户不存在的错误信息
					errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.java.alert20");
					userContext.setErrorMessage(errorMessage);
				}
			} catch (final ServiceException e) {
				// 更新数据出现异常
				e.printStackTrace();
				errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.jsp.alert21");
				userContext.setErrorMessage(errorMessage);
			} finally {
				try {
					response.getWriter().write(JSONFactory.toJSONString(entity, userContext));
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
